<template>
  <div class="RequirementRelease">
    <h2>需求详情</h2>

    <div class="main">
      <a-form :form="form" @submit="handleSubmit">
        <h3>基本信息</h3>

        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="需求名称">
          <a-input :maxLength=101 v-decorator="[
              'demandProductName',
              { rules: [
                { required: true,message:'请输入需求产品名称' },
                { max:100,message:'该内容最多为100个字'}
              ],
                initialValue:defultForm.demandProductName },
            ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="产品同义名称">
          <a-input :maxLength=101 v-decorator="[
              'productSynonymName',
              { rules: [{ max:100,message:'该内容最多为100个字'}],
                initialValue:defultForm.productSynonymName}
            ]" />
          <em>多个名称使用分隔符(;)进行区分</em>
        </a-form-item>
        <a-form-item required :label-col="formTailLayout.labelCol" :wrapper-col="{span:15}" label="产品类别">
          <div class="clearfix">
            <a-form-item class="f-left mr-32">
              <a-select placeholder="请选择" style="width: 250px" @change="handleChange" v-decorator="['productOneCategory',{ rules: productOneCategoryRules,initialValue:defultForm.productOneCategory}]">
                <a-select-option v-for="(item,index) in selectType" :key="index" :value="item.categoryNo">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="f-left mr-32">
              <a-select placeholder="请选择" style="width: 250px" @change="handleChange1"
                v-decorator="['productSecondCategory',{ rules: productSecondCategoryRules,initialValue:defultForm.productSecondCategory},]">
                <a-select-option v-for="(item, index) in selectType1" :key="index" :value="item.categoryNo">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="f-left">
              <a-input :maxLength=101 style="width:250px" v-decorator="[
                'productThirdCategory',
                { rules: [
                  { required: true,message:'请输入规则型号' },
                  { max:1000,message:'该内容最多为100个字'}
                ],initialValue:defultForm.productThirdCategory },
              ]" />
            </a-form-item>
            <!-- </a-form-item> -->
          </div><em>可输入小类，多个名称使用分隔符（;）进行区分</em>
        </a-form-item>
        <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol" label="规格型号">
          <a-input :maxLength=1001 type="textarea" :rows="5" v-decorator="[
                'productSpec',
                { rules: [
                  { required: true,message:'请输入规则型号' },
                  { max:1000,message:'该内容最多为1000个字'}
                ],initialValue:defultForm.productSpec },
              ]" /><em>多个名称使用分隔符(;)进行区分</em>
        </a-form-item>
        <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol" label="概述">
          <a-input type="textarea" :rows="5" v-decorator="[
                'demandDetails',
                { initialValue:defultForm.demandDetails },
              ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="{span:4}" label="预算价格">
          <a-input suffix="元" v-decorator="['price',
          {initialValue:defultForm.price},
          {rules: [
          { 
            pattern:/^(\+)?\d+(\.\d+)?$/,
            message:'该内容必须为数字' 
          }
          ],},]" />
        </a-form-item>
        <a-form-item class="clearfix" required :label-col="formItemLayout.labelCol" :wrapper-col="{span:8}" label="截止日期">
          <a-date-picker class="f-left" @change="dataChange" :disabled-date="disabledDate" v-decorator="[
            'expirationDate',
            { rules: dataRules,initialValue:(defultForm.expirationDate?defultForm.expirationDate:null) },
            ]" />
          <a-form-item class="f-left ml-20">
            <a-checkbox :checked="checkNick" @change="checkChange" v-decorator="['isLongTime']">长期需求</a-checkbox>
          </a-form-item>
        </a-form-item>

        <h3>联系方式</h3>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="联系人">
          <a-input v-decorator="[
              'contacts',
              { rules: [{ required: true,message:'请输入联系人' }],
              initialValue:defultForm.contacts },
            ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="手机号码">
          <a-input v-decorator="[
              'phone',
              { rules: [
                { required: true,message:'请输入手机号码' },
                {
                  pattern:  /^1[3456789]\d{9}$/,
                  message: '手机号码格式不正确'
                }
              ],initialValue:defultForm.phone  },
            ]" />
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="电子邮箱">
          <a-input v-decorator="[
              'email',
              { rules:[
                {
                  pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
                  message: '邮箱格式不正确'
              }],initialValue:defultForm.email}
            ]" />
        </a-form-item>
        <!-- <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
          <a-button class="mr-20" @click="clear">
            取消
          </a-button>
          <a-button type="primary" html-type="submit">
            提交
          </a-button>
        </a-form-item> -->
      </a-form>
    </div>
    <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
      <a-button @click="clear">返回</a-button>
    </a-form-item>
  </div>
</template>

<script>
import moment from "moment";
import {
  GetSearchinfo,
  GetByParent,
  UpdateMaterialsDemand,
} from "@/apis/user/MaterialsDemand";
const formItemLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 8 },
};
const formTailLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 12 },
};
export default {
  data() {
    return {
      productOneCategoryRules: [{ required: true, message: "请选择一级类别" }],
      productSecondCategoryRules: [
        { required: false, message: "请选择二级类别" },
      ],
      dataRules: [{ required: false, message: "请输入截止日期" }],
      checkNick: false,
      selectType: [],
      selectType1: [],
      checkNick: true,
      isLongTime: 1,
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this),
      formLine: {},
      infoList: {},
      defultForm: {
        id: this.id,
      },
    };
  },
  created() {
    this.GetByParentList();
    console.log(this.$route.query.id);
    if (this.$route.query.id) {
      this.defultForm.id = this.$route.query.id;
      this.GetSearchinfo(this.defultForm.id);
    }
  },
  methods: {
    //日期判断今天之前不可选（不包含今天）
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().subtract(1, "days").endOf("day");
    },
    dataChange(e) {
      console.log(e);
      if (e == null) {
        // this.dataRules[0].required = true
        this.checkNick = true;
        this.isLongTime = 1;
      } else {
        this.dataRules[0].required = false;
        this.checkNick = false;
        this.isLongTime = 0;
      }
    },
    checkChange(e) {
      this.checkNick = e.target.checked;
      if (this.checkNick) {
        this.dataRules[0].required = false;
        this.isLongTime = 1;
      } else {
        this.dataRules[0].required = true;
        this.isLongTime = 0;
      }
      this.form.setFieldsValue({
        expirationDate: "",
      });
    },
    handleSubmit(e) {
      console.log(e);
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          values.expirationDate = moment(values.expirationDate).format(
            "YYYY-MM-DD"
          );
          this.defultForm.demandProductName = values.demandProductName;
          this.defultForm.productSynonymName = values.productSynonymName;
          this.defultForm.productOneCategory = values.productOneCategory;
          this.defultForm.productSecondCategory = values.productSecondCategory;
          this.defultForm.productThirdCategory = values.productThirdCategory;
          this.defultForm.productSpec = values.productSpec;
          this.defultForm.demandDetails = values.demandDetails;
          this.defultForm.price = values.price;
          if (values.isLongTime == true) {
            this.defultForm.expirationDate = undefined;
          } else {
            this.defultForm.expirationDate = values.expirationDate;
          }
          // this.defultForm.expirationDate = values.expirationDate;
          this.defultForm.isLongTime = this.isLongTime;
          this.defultForm.contacts = values.contacts;
          this.defultForm.phone = values.phone;
          this.defultForm.email = values.email;
          console.log(this.defultForm);
          this.UpdateMaterialsDemand();
          setTimeout(() => {
            // 清空表单
            this.form.resetFields();
          }, 1000);
        }
      });
    },
    clear() {
      //跳回需求页
      this.$router.push("/usercenter/MyNeed");
    },

    // 产品分类下拉列表
    GetByParentList() {
      GetByParent().then((res) => {
        // console.log(res)
        if (res.code == 200) {
          this.selectType = res.data;
        }
      });
    },
    //修改
    UpdateMaterialsDemand() {
      let formData = JSON.parse(JSON.stringify(this.defultForm))
      formData.price = formData.price === '' || formData.price === null ? '0' : formData.price
      formData.email = formData.email === '' || formData.email === null ? '' : formData.email
      UpdateMaterialsDemand(formData).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.loading({ content: "Loading..." });
          setTimeout(() => {
            this.$message.success({ content: "修改成功", duration: 2 });
            //跳回需求页
            this.$router.push("/usercenter/MyNeed");
          }, 3000);
        } else {
          this.$message.warning("修改失败");
        }
      });
    },
    handleChange(value) {
      console.log(value);
      this.productOneCategoryRules[0].required = true;
      this.productSecondCategoryRules[0].required = true;
      let id = "";
      this.selectType.map((item, index) => {
        if (item.categoryNo == value) {
          id = item.id;
        }
      });
      let params = { pid: id };
      GetByParent(params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.selectType1 = res.data;
        }
      });
    },
    handleChange1(value) {
      console.log(value);
    },
    // 获取需求列表
    GetSearchinfo(id) {
      GetSearchinfo({ id }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.defultForm = res.data;
          this.defultForm.price = this.defultForm.price === 0 ? '' : this.defultForm.price
          if (this.defultForm.isLongTime == 1) {
            this.checkNick = true;
            this.form.setFieldsValue({
              expirationDate: "",
            });
          } else if (this.defultForm.isLongTime == 0) {
            this.checkNick = false;
          }
          console.log(this.defultForm);

          let id = "";
          this.selectType.map((item, index) => {
            if (item.categoryNo == this.defultForm.productOneCategory) {
              id = item.id;
            }
          });
          let params = { pid: id };
          console.log(params);
          GetByParent(params).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.selectType1 = res.data;
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 8px;
}
.RequirementRelease {
  padding: 17px 24px;
  background: #fff;
  h2 {
    font-size: 22px;
    line-height: 17px;
    color: #303133;
    padding-bottom: 14px;
    border-bottom: solid 1px #e9e9e9;
  }

  .main {
    pointer-events: none;
    h3 {
      margin: 16px 0;
      padding-left: 16px;
      height: 48px;
      line-height: 48px;
      font-weight: 700;
      font-size: 16px;
      color: #303133;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
em {
  font-size: 14px;
  color: #909399;
}
</style>